package com.sinosoft.hbzyy.app.wms.base.data.provider;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonParseException;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;
import com.sinosoft.framework.core.common.utils.string.PymUtils;
import com.sinosoft.hbzyy.app.wms.base.data.api.DepartmentService;
import com.sinosoft.hbzyy.app.wms.base.data.dao.DepartmentMapper;
import com.sinosoft.hbzyy.app.wms.base.data.dao.DoctorUserMapper;
import com.sinosoft.hbzyy.app.wms.base.data.dao.ParentDeptMapper;
import com.sinosoft.hbzyy.app.wms.base.data.model.DepartmentEntity;
import com.sinosoft.hbzyy.app.wms.base.data.model.DeptDto;
import com.sinosoft.hbzyy.app.wms.base.data.model.DistrictEntity;
import com.sinosoft.hbzyy.app.wms.base.data.model.ParentDeptDto;
import com.sinosoft.hbzyy.app.wms.base.data.model.ParentDeptEntity;
import com.sinosoft.hbzyy.app.wms.base.data.util.NeteaseClient;
import com.sinosoft.hbzyy.framework.core.api.model.PageList;
import com.sinosoft.hbzyy.framework.util.ResultHelper;

/**
 * 
 * @author 刘富鹏
 * @description:科室信息服务实现类
 * @date：2018年3月20日下午3:33:22
 * @type：DepartmentServiceImpl
 * @version: 1.0
 * @company:中科软
 */
public class DepartmentServiceImpl implements DepartmentService {

	private static final Logger logger = Logger.getLogger(DepartmentServiceImpl.class);
	private DepartmentMapper departmentMapper;
	
	private DoctorUserMapper doctorUserMapper;
	
	private ParentDeptMapper parentDeptMapper;

	public void setDepartmentMapper(DepartmentMapper departmentMapper) {
		this.departmentMapper = departmentMapper;
	}

	public void setDoctorUserMapper(DoctorUserMapper doctorUserMapper) {
		this.doctorUserMapper = doctorUserMapper;
	}

	public void setParentDeptMapper(ParentDeptMapper parentDeptMapper) {
		this.parentDeptMapper = parentDeptMapper;
	}

	@Override
	@Transactional(rollbackFor=RuntimeException.class)
	public Map<String, Object> createDepartment(List<DepartmentEntity> departs) throws JsonParseException, IOException, RuntimeException {
		DepartmentEntity de = null;
		for(DepartmentEntity depart : departs) {
			de = departmentMapper.getDeptByDeptCode(depart.getOrgCode(), depart.getDeptCode());
			if(de != null) {
				throw new RuntimeException("科室已存在，科室名为："+de.getOrgName()+de.getDeptName());
			}
			depart.setId(UUID.randomUUID().toString());
			String accid=UUID.randomUUID().toString().replaceAll("_", "");
			NeteaseClient.creat(accid, depart.getDeptCode());
			depart.setAccid(accid);
			depart.setDeptNamePy(PymUtils.convert2Py(depart.getDeptName()));
			depart.setCreateAt(System.currentTimeMillis());
			depart.setOrgName(depart.getOrgName()+"("+depart.getOrgIdName()+")");
			departmentMapper.createDepartment(depart);
		}
		return ResultHelper.buildSuccessResult("保存成功");
	}

	@Override
	public Map<String, Object> updateDepartment(DepartmentEntity depart) {
		try {
			depart.setUpdateAt(System.currentTimeMillis());
			if(depart.getOrgIdName() == null || depart.getOrgIdName().equals("")) {
				depart.setOrgName(null);
			}
			departmentMapper.updateDepartment(depart);
			return ResultHelper.buildSuccessResult(depart);
		} catch (Exception e) {
			return ResultHelper.buildErrorResult("更新数据："+e.getMessage());
		}
	}

	@Override
	public List<DepartmentEntity> retrieveDepartment(String id,String orgId,String orgName,String orgCode,String deptName,String parentCode ,int currentPage,int rows) {
		
		List<DepartmentEntity> departs = departmentMapper.retrieveDepartment(id,orgId,orgName,orgCode,deptName,parentCode, currentPage, rows);
		//int count = departmentMapper.retrieveDepartmentCount(id,orgId,orgName,orgCode,deptName,parentCode);
		//PageList<DepartmentEntity> pageList=new PageList<DepartmentEntity>();
//		pageList.setDatas(departs);
//		pageList.setPageNum(currentPage);
//		pageList.setPageSize(rows);
//		pageList.setTotal(count);
		return departs;
	}

	@Override
	public Map<String, Object> retrieveDepartmentByDeptCode(String deptCode) {
		List<DepartmentEntity> departs = departmentMapper.retrieveDepartmentByDeptCode(deptCode);
		return ResultHelper.buildSuccessResult(departs);
	}

	@Override
	public Map<String, Object> retrieveDepartmentByOrgCode(String orgCode) {
		List<DepartmentEntity> departs = departmentMapper.retrieveDepartmentByOrgCode(orgCode);
		return ResultHelper.buildSuccessResult(departs);
	}
	

	@Override
	public Map<String, Object> updateDepartmentByDeptCode(String deptCode,String status) {
		try {
			departmentMapper.updateDepartmentByDeptCode(deptCode,status);
			doctorUserMapper.updateDoctDeptByDeptCode(deptCode,status);
			return ResultHelper.buildSuccessResult("状态修改成功");
		} catch (Exception e) {
			return ResultHelper.buildErrorResult("状态修改失败");
		}
	}

	@Override
	public Map<String, Object> deleteDepartmentByOrgCode(String orgCode) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Map<String, Object> getOrgNameByOrgCode(String orgCode) {
		List<DistrictEntity> datas = new ArrayList<>();
		try {
			datas = departmentMapper.getOrgNameByOrgCode(orgCode);
		} catch (Exception e) {
			e.printStackTrace();
			return ResultHelper.buildErrorResult("数据库异常");
		}
		return ResultHelper.buildSuccessResult(datas);
	}

	@Override
	public Map<String, Object> deleteDepartmentById(String id) {
		try {
			departmentMapper.deleteDepartmentById(id);
			return ResultHelper.buildSuccessResult("删除成功");
		} catch (Exception e) {
			e.printStackTrace();
			return ResultHelper.buildErrorResult(e.getMessage());
		}
	}

	@Override
	public Map<String,Object> retrieveDepartments(String orgId, String orgCode,String deptName,int currentPage,int rows) {
		
		List<DepartmentEntity> departs = departmentMapper.retrieveDepartments(orgId,orgCode, deptName,currentPage, rows);
		int count = departmentMapper.retrieveDepartmentsCount(orgId,orgCode,deptName);
		PageList<DepartmentEntity> pageList=new PageList<DepartmentEntity>();
		pageList.setDatas(departs);
		pageList.setPageNum(currentPage);
		pageList.setPageSize(rows);
		pageList.setTotal(count);
		return ResultHelper.buildSuccessResult(pageList);

	}

	@Override
	public Map<String, Object> retrieveAllDept(String orgCode,String orgId,String deptName) {
		if(StringUtils.isBlank(orgCode)) {
			logger.error("机构编码不能为空");
			return ResultHelper.buildErrorResult("查询失败,请稍后重试");
		}
		if(StringUtils.isBlank(orgId)) {
			logger.error("院区编码不能为空");
			return ResultHelper.buildErrorResult("查询失败,请稍后重试");
		}
		if(deptName==null) {
			deptName = "";
		}
		List<ParentDeptDto> parentDtoList = Lists.newArrayList();
		List<ParentDeptDto> newParentDtoList = Lists.newArrayList();
		try {
			parentDtoList = parentDeptMapper.retrieveParentDeptDto(orgCode, orgId,deptName);
			for(ParentDeptDto deptDto:parentDtoList) {
				if(!deptDto.getDepartList().isEmpty()) {
					newParentDtoList.add(deptDto);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("数据库异常，查询科室信息失败"+e.getMessage());
			return ResultHelper.buildSuccessResult("查询失败,请稍后重试");
		}
		
		return ResultHelper.buildSuccessResult(newParentDtoList);
	}

	@Override
	public Map<String, Object> retrieveDepart(String orgCode, String orgId, String deptName) {
        List<DepartmentEntity> departList = Lists.newArrayList();
        List<DepartmentEntity> newDepartList = Lists.newArrayList();
        List<ParentDeptEntity> parentList = Lists.newArrayList();
        //ParentDeptEntity parentDeptEntity = new ParentDeptEntity();
        List<ParentDeptDto> parentDtoList = Lists.newArrayList();
        //全部的父科室
        parentList = parentDeptMapper.retrieveParentDept(orgCode, null, null);
        //departList = departmentMapper.retrieveDepartByDeptName(orgId, orgCode, deptName);
        for(ParentDeptEntity parentDeptEntitys:parentList) {
             departList = departmentMapper.retrieveDepartByDeptName(orgId, orgCode, deptName);
//        	 if(parentDeptEntitys.getCode().equals(depart.getParentCode())) {
//        		 ParentDeptDto parentDto =  new ParentDeptDto();
//        		 //newDepartList.add(depart);
//                 parentDto.setCode(parentDeptEntitys.getCode());
//                 parentDto.setCreateAt(parentDeptEntitys.getCreateAt());
//                 parentDto.setCreateBy(parentDeptEntitys.getCreateBy());
//                 parentDto.setDepartList(departList);
//                 parentDto.setId(parentDeptEntitys.getId());
//                 parentDto.setName(parentDeptEntitys.getName());
//                 parentDto.setOrgId(parentDeptEntitys.getOrgId());
//                 parentDto.setOrgName(parentDeptEntitys.getOrgName());
//                 parentDto.setRemark(parentDeptEntitys.getRemark());
//                 parentDto.setStatus(parentDeptEntitys.getStatus());
//                 parentDto.setUpdateAt(parentDeptEntitys.getUpdateAt());
//                 parentDto.setUpdateBy(parentDeptEntitys.getUpdateBy());
//                 parentDtoList.add(parentDto);
//        	 
//           }

          
        }
        return ResultHelper.buildSuccessResult(parentDtoList);
	}

	//去掉重复的parentcode
    private static ArrayList<DepartmentEntity> removeDuplicateDepart(List<DepartmentEntity> depart) {
        //使用set集合处理对象的时候，通常我们需要重写hashcode和equals方法 
    	Set<DepartmentEntity> set = new TreeSet<DepartmentEntity>(new Comparator<DepartmentEntity>() {

			@Override
			public int compare(DepartmentEntity o1, DepartmentEntity o2) {
				return o1.getParentCode().compareTo(o2.getParentCode());
			}
        	 
         });
           return new ArrayList<DepartmentEntity>(set);
    }

}
